//
//  MathTool.swift
//  VO_Yuejie
//
//  Created by laichunhui on 15/11/20.
//  Copyright © 2015年 lch. All rights reserved.
//

import Foundation

struct MathTool {
    /// 弧度 -> 角度
    static func radiansToDegrees(x: CGFloat) -> CGFloat {
        return 180.0 * x / CGFloat(M_PI)
    }
    
    /// 角度 -> 弧度
    static func degreesToRadian(x: CGFloat) -> CGFloat {
        return x * CGFloat(M_PI) / 180.0
    }
    
    /// 两点直线距离
    static func distanceBetweenPoints(firstP: CGPoint, secondP: CGPoint) -> CGFloat {
        let deltaX = secondP.x - firstP.x
        let deltaY = secondP.y - firstP.y
        
        return sqrt(deltaX * deltaX + deltaY * deltaY)
    }
    
    /// 两点之间的角度 (以起点为坐标原点，x轴为参照线，取值 0..<360 顺时针计算，第一象限对应数学中的第四象限)
    static func angleBetweenPoints(startP: CGPoint, endP: CGPoint) -> CGFloat {
       
        let offsetY: CGFloat = endP.y - startP.y
        let offsetX: CGFloat =   endP.x - startP.x
//        let rads: CGFloat = atan(fabs(offsetY / offsetX))
              let rads: CGFloat = atan(offsetY / offsetX)

        let angle:CGFloat = radiansToDegrees(rads)
 
        if offsetX >= 0 && offsetY > 0 { //第一象限
            return fabs(angle)
        } else if offsetX < 0 && offsetY > 0 { //第二象限
            return angle + 180
        } else if offsetX < 0 && offsetY <= 0 { //第三象限
            return angle + 180
        } else if offsetX >= 0 && offsetY < 0 { //第四象限
            return 360 + angle
        } else {
            return angle
        }
    }
    
    /// 两线夹角
    static func angleBetweenLines(line1Start: CGPoint, line1End: CGPoint, line2Start: CGPoint, line2End: CGPoint) -> CGFloat {
        let a: CGFloat = line1End.x - line1Start.x
        let b: CGFloat = line1End.y - line1Start.y
        let c: CGFloat = line2End.x - line2Start.x
        let d: CGFloat = line2End.y - line2Start.y
        let rads: CGFloat = acos(((a * c) + (b * d)) / ((sqrt(a * a + b * b)) * (sqrt(c * c + d * d))))
        return radiansToDegrees(rads)
    }
 
}